package org.mozhu.learning.algo.stack;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 基于数组实现的Stack，可以动态扩容
 */
public class StackOfArray<E> implements Stack<E> {

    private E[] a = (E[]) new Object[16];

    private int size = 0;

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public void push(E element) {
        if (size == a.length) {
            resize();
        }
        a[size] = element;
        size++;
    }

    private void resize() {
        a = Arrays.copyOf(a, size << 1);
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        size--;
        E result = a[size];
        a[size] = null; // clear
        return result;
    }

    @Override
    public E peak() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return a[size - 1];
    }
}
